package top.wardyan.common.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 封装各种hash算法:
 * MD5     
 * SHA-1
 * SHA-256
 * SHA-384
 * SHA-512
 * @author feng
 *
 */
public class HashUtil {
	
	
	public static String MD5(String text) {
		String rs = "";
		try {
			rs = encrypt(text, "MD5");
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return rs;
	}
	
	public static String SHA256(String text) {
		String rs = "";
		try {
			rs = encrypt(text, "SHA-256");
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return rs;
	}
	public static String SHA512(String text) {
		String rs = "";
		try {
			rs = encrypt(text, "SHA-512");
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return rs;
	}
	
	 
	  /** @param source 需要加密的字符串
	   * @param hashType  加密类型 （MD5 和 SHA）如下:
	   * MD5     
	   * SHA-1
	   * SHA-256
	   * SHA-384
	   * SHA-512
	   * @return
	   */
	public static String encrypt(String source, String hashType) throws NoSuchAlgorithmException {
		StringBuilder sb = new StringBuilder();
		MessageDigest md5;
		md5 = MessageDigest.getInstance(hashType);
		md5.update(source.getBytes());
		var bytes = md5.digest();
		for (byte b : bytes) {
			sb.append(String.format("%02X", b)); // 10进制转16进制，X 表示以十六进制形式输出，02 表示不足两位前面补0输出
		}
		return sb.toString();
	}
	
	
	public static void main(String[] args) {
		// var ok = Security.getProviders();
		System.out.println(SHA256("hello"));
		System.out.println(SHA512("hello"));
	}

}
